#!/usr/bin/env python3
"""
macOS系统配置模块

专门处理macOS系统下的各种警告和配置问题，包括：
1. IMKCFRunLoopWakeUpReliable 输入法警告
2. OpenCV摄像头权限警告
3. 其他macOS系统相关警告

使用方法：
```python
from kidsbuddy.utils.macos_config import configure_macos_environment
configure_macos_environment()
```
"""

import os
import sys
import warnings
import logging
import platform


def configure_macos_environment(verbose: bool = True) -> None:
    """
    配置macOS环境，抑制系统警告
    
    参数:
        verbose: 是否显示配置信息
    """
    if platform.system() != 'Darwin':
        if verbose:
            print("ℹ️  非macOS系统，跳过macOS特定配置")
        return
    
    if verbose:
        print("🍎 检测到macOS系统，正在配置环境...")
    
    # 1. 抑制输入法相关警告
    _suppress_input_method_warnings(verbose)
    
    # 2. 配置OpenCV相关设置
    _configure_opencv_settings(verbose)
    
    # 3. 抑制Python系统警告
    _suppress_system_warnings(verbose)
    
    # 4. 配置日志级别
    _configure_logging_levels(verbose)
    
    if verbose:
        print("✅ macOS环境配置完成")


def _suppress_input_method_warnings(verbose: bool = True) -> None:
    """抑制输入法相关警告"""
    try:
        # 抑制IMKCFRunLoopWakeUpReliable相关警告
        warnings.filterwarnings("ignore", message=".*IMKCFRunLoopWakeUpReliable.*")
        warnings.filterwarnings("ignore", message=".*mach port.*")
        warnings.filterwarnings("ignore", message=".*messaging the mach port.*")
        
        # 设置环境变量
        os.environ['PYTHONWARNINGS'] = 'ignore'
        
        if verbose:
            print("  ✓ 输入法警告抑制已配置")
            
    except Exception as e:
        if verbose:
            print(f"  ⚠️  输入法警告配置失败: {e}")


def _configure_opencv_settings(verbose: bool = True) -> None:
    """配置OpenCV相关设置"""
    try:
        # 跳过摄像头权限检查
        os.environ['OPENCV_AVFOUNDATION_SKIP_AUTH'] = '1'
        
        # 禁用一些可能导致警告的OpenCV功能
        os.environ['OPENCV_VIDEOIO_PRIORITY_MSMF'] = '0'
        os.environ['OPENCV_VIDEOIO_DEBUG'] = '0'
        
        if verbose:
            print("  ✓ OpenCV设置已配置")
            
    except Exception as e:
        if verbose:
            print(f"  ⚠️  OpenCV配置失败: {e}")


def _suppress_system_warnings(verbose: bool = True) -> None:
    """抑制Python系统警告"""
    try:
        # 抑制各种系统警告
        warnings.filterwarnings("ignore", category=UserWarning)
        warnings.filterwarnings("ignore", category=DeprecationWarning)
        warnings.filterwarnings("ignore", category=FutureWarning)
        
        # 抑制特定的macOS相关警告
        warnings.filterwarnings("ignore", message=".*CoreFoundation.*")
        warnings.filterwarnings("ignore", message=".*NSApplication.*")
        warnings.filterwarnings("ignore", message=".*Cocoa.*")
        
        if verbose:
            print("  ✓ 系统警告抑制已配置")
            
    except Exception as e:
        if verbose:
            print(f"  ⚠️  系统警告配置失败: {e}")


def _configure_logging_levels(verbose: bool = True) -> None:
    """配置日志级别"""
    try:
        # 设置根日志级别
        logging.getLogger().setLevel(logging.ERROR)
        
        # 设置特定库的日志级别
        loggers_to_silence = [
            'PIL',
            'matplotlib',
            'urllib3',
            'requests',
            'cv2',
            'numpy'
        ]
        
        for logger_name in loggers_to_silence:
            logging.getLogger(logger_name).setLevel(logging.ERROR)
        
        if verbose:
            print("  ✓ 日志级别已配置")
            
    except Exception as e:
        if verbose:
            print(f"  ⚠️  日志配置失败: {e}")


def is_macos() -> bool:
    """检查是否为macOS系统"""
    return platform.system() == 'Darwin'


def get_macos_version() -> str:
    """获取macOS版本信息"""
    if not is_macos():
        return "Not macOS"
    
    try:
        import subprocess
        result = subprocess.run(['sw_vers', '-productVersion'], 
                              capture_output=True, text=True)
        return result.stdout.strip()
    except Exception:
        return "Unknown"


def configure_for_opencv_gui() -> None:
    """专门为OpenCV GUI应用配置macOS环境"""
    if not is_macos():
        return
    
    # 设置GUI相关的环境变量
    os.environ['QT_MAC_WANTS_LAYER'] = '1'
    os.environ['OPENCV_AVFOUNDATION_SKIP_AUTH'] = '1'
    
    # 抑制GUI相关警告
    warnings.filterwarnings("ignore", message=".*Qt.*")
    warnings.filterwarnings("ignore", message=".*GUI.*")


if __name__ == "__main__":
    # 测试配置
    print("🧪 测试macOS环境配置")
    print(f"系统: {platform.system()}")
    print(f"macOS版本: {get_macos_version()}")
    
    configure_macos_environment(verbose=True)
    configure_for_opencv_gui()
    
    print("\n✅ 配置测试完成")
